<script lang="ts" setup>
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app"
import { ref } from "vue"
import { getHotListApi } from "@/api/hot";
import { HotSortType } from "@/enum/hotSortType";
import type { HotAnimalItem } from "@/types/hot";
import Skeleton from "@/pages/hot/components/Skeleton.vue";
import { ImgErrorType } from "@/enum/imgErrorType";

const { safeAreaInsets, windowWidth } = uni.getSystemInfoSync()

onPullDownRefresh(() => {
  networkError.value = false
  if (activeIndex.value === HotSortType.SEARCH) {
    getHotSearch()
  } else if (activeIndex.value === HotSortType.SCORE) {
    getHotScore()
  }

  uni.stopPullDownRefresh()
})

const isFinish = ref(false) // 请求是否完成
const isFinishSearchImg = ref<boolean[]>([]) // 图片渲染是否完成
const isFinishScoreImg = ref<boolean[]>([]) // 图片渲染是否完成
/**
 * 图片渲染完成
 * @param index 完成索引
 * @param type 完成类型
 */
const onFinishImg = (index: number, type: HotSortType) => {
  if (type === HotSortType.SEARCH) {
    isFinishSearchImg.value[index] = true
  } else if (type === HotSortType.SCORE) {
    isFinishScoreImg.value[index] = true
  }
}
// 当前激活的榜单
const activeIndex = ref(0)
const onSwiperChange: UniHelper.SwiperOnChange = (event) => {
  activeIndex.value = event.detail.current
  if (hotScoreList.value.length < 1) { // 默认不先发起请求
    getHotScore()
  }
}

// 监听页面滚动事件
const moveX = ref(0)
const startX = ref(windowWidth * 0.2)
const swiperWidth = ref(Number(Number(windowWidth * 0.95).toFixed(0)))
const onTouchMove: UniHelper.SwiperOnTransition = (e) => {
  moveX.value = e.detail.dx! / 2.3
}
//点击切换
const onChangeHot = (type: HotSortType) => {
  activeIndex.value = type
}
/**
 *  监听滑动结束
 * @param event
 */
const onChangeOver: UniHelper.SwiperOnAnimationfinish = (event) => {
  if (event.detail.current === 0) {
    startX.value = windowWidth * 0.2
    moveX.value = 0
  } else if (event.detail.current === 1) {
    startX.value = windowWidth * 0.62
    moveX.value = 0
  }
}

/* 获取热门数据*/
const hotSearchList = ref<HotAnimalItem[]>([])
const hotScoreList = ref<HotAnimalItem[]>([])
const getHotSearch = async () => {
  const res = await getHotListApi(HotSortType.SEARCH, 1, 50) // 搜索度
  hotSearchList.value = res.data.data
  isFinish.value = true
}
const getHotScore = async () => {
  uni.showLoading({ title: '加载中...' })
  const res = await getHotListApi(HotSortType.SCORE, 1, 50) // 评分
  hotScoreList.value = res.data.data
  uni.hideLoading()
}
onLoad(async () => {
  await getHotSearch() // 默认先获取搜索优先
  isFinishScoreImg.value = new Array(hotScoreList.value.length).fill(false)
  isFinishScoreImg.value = new Array(50).fill(false)
})
// 点击热门动物
const goDetail = (id: string) => {
  uni.navigateTo({
    url: `/subPkg/detail/detail?id=${id}`
  })
}
/* 异常处理*/
/**
 * 图片异常——拿到图片地址但获取图片失效
 * @param index 错误索引
 * @param type 错误类型
 */
const onErrorImg = (index: number, type: HotSortType) => {
  if (type === HotSortType.SEARCH) {
    isFinishSearchImg.value[index] = true
    hotSearchList.value[index].img = ImgErrorType.ERROR_IMG_URL
  } else {
    isFinishScoreImg.value[index] = true
    hotScoreList.value[index].img = ImgErrorType.ERROR_IMG_URL
  }
}

// 网络异常
const networkError = ref(false)
uni.$on('noNetwork', () => {
  if (!isFinish.value) {
    networkError.value = true
  }
  uni.showToast({title: '网络异常，请稍检查网络', icon: 'none'})
  uni.stopPullDownRefresh()
})
</script>

<template>
  <aw-no-network v-if="networkError"></aw-no-network>
  <view v-else>
    <view v-if="!isFinish">
      <Skeleton  />
    </view>
    <view v-else class="hot">
      <!--   热榜顶部区域   -->
      <!--    <view :style="{'padding-top': safeAreaInsets?.top + 'px'}"
                class="hot-title bg-gradual-awGreen text-white text-xxl">排行榜
            <text class="cuIcon-rank margin-left-xs" style="font-size: 56rpx"></text>
          </view>-->
      <view style="width: 100%;position: fixed; top: 0;z-index: 100;backdrop-filter: blur(15px)" class="flex flex-column justify-center align-center">
        <!--   热榜第一封面   -->
        <view class="hot-first">
          <view class="cover-text text-white padding-left-sm">{{ activeIndex === 0 ? '搜索指数' : '评分' }}最高——
            <text class="text-awGreen text-xl" style="font-weight: 500">
              {{ activeIndex === 0 ? hotSearchList[0]?.name : hotScoreList[0]?.name }}
            </text>
          </view>
          <image :src="activeIndex === HotSortType.SEARCH ? hotSearchList[0]?.img : hotScoreList[0]?.img" mode="aspectFill"
                 style="width: 100%;height: 230rpx">
          </image>

        </view>
        <!--   排行切换 -->
        <view :style="{ '--width': windowWidth + 'px', '--startX': startX + 'px' }" class="hot-category round">
          <view :class="{ active: activeIndex === HotSortType.SEARCH }" class="hot-category-item"
                @click="onChangeHot(HotSortType.SEARCH)">热度
          </view>
          <view :class="{ active: activeIndex === HotSortType.SCORE }" class="hot-category-item"
                @click="onChangeHot(HotSortType.SCORE)">评分
          </view>
          <view :style="{ transform: `translateX(${moveX}px)` }" class="under-line round bg-gradual-awGreen"></view>
        </view>

      </view>

      <!--   列表展示 -->
      <view :style="{ '--swiper': swiperWidth + 'px' }" class="hot-list">
        <swiper :current="activeIndex" class="hot-list-swiper" style="height: 80vh;" @animationfinish="onChangeOver"
                @change="onSwiperChange" @transition="onTouchMove">
          <swiper-item class="hot-list-swiper-item" style="height: 100%">
            <scroll-view :scroll-y="true" style="height: 100%">
              <view v-for="(item, index) in hotSearchList" :key="item.id" class="hot-list-item" @tap="goDetail(item.id)">
                <view class="hot-list-item-left ">
                  <image v-show="isFinishSearchImg[index]"
                         :mode="hotSearchList[index].img === ImgErrorType.ERROR_IMG_URL ? 'aspectFit' : 'aspectFill'"
                         :src="item.img ? item.img : ImgErrorType.ERROR_IMG_URL" style="border-radius: 10rpx"
                         @error="onErrorImg(index, HotSortType.SEARCH)" @load="onFinishImg(index, HotSortType.SEARCH)"></image>
                  <image v-show="!isFinishSearchImg[index]" mode="aspectFit" src="/static/home-selected.png"></image>
                </view>
                <view class="hot-list-item-right padding-left-sm padding-tb-xs">
                  <view class="name text-lg flex justify-start">{{ item.name }}
                    <view class="search text-awGreen text-lg margin-left-sm" style="font-style: italic">
                      {{ item.searchCount! * 100 }}
                      <text v-show="item.searchCount! > 100" class="cuIcon-hot line-red"></text>
                    </view>
                  </view>
                  <view class="score flex justify-start align-center">
                    <uni-rate :value="item.score! / 20" allow-half color="#c7c7c7" readonly size="14" />
                    <text class="text-gray margin-left-xs text-df">{{ Number(item.score! / 10).toFixed(1) }}</text>
                  </view>
                  <text class="desc text-df text-gray">
                    {{ item.desc }}
                  </text>
                  <view class="justify-end text-sm  margin-top-xs"
                        style="max-width: 420rpx;max-height:30rpx;overflow: hidden">
                    <text v-for="(tag, tagIndex) in item.tags?.split(',')" :key="tag + tagIndex"
                          class="cu-tag round margin-right-xs bg-gray sm" style="color: #8d8d8d">
                      {{ tag }}
                    </text>
                  </view>
                </view>
              </view>
              <view class="flex justify-center align-center margin-bottom-xl text-gray" style="width: 100%">
                榜单只展示前50的动物哟ヾ(≧▽≦*)o
              </view>
            </scroll-view>
          </swiper-item>

          <swiper-item class="hot-list-swiper-item" style="height: 100%">
            <scroll-view :scroll-y="true" style="height: 100%">
              <view v-for="(item, index) in hotScoreList" :key="item.id" class="hot-list-item" @click="goDetail(item.id)">
                <view class="hot-list-item-left ">
                  <image v-show="isFinishScoreImg[index]" :lazy-load="true"
                         :mode="hotScoreList[index].img === ImgErrorType.ERROR_IMG_URL ? 'aspectFit' : 'aspectFill'" :src="item.img"
                         style="border-radius: 10rpx" @error="onErrorImg(index, HotSortType.SCORE)"
                         @load="onFinishImg(index, HotSortType.SCORE)"></image>
                  <image v-show="!isFinishScoreImg[index]" mode="aspectFit" src="/static/home-selected.png"></image>
                </view>
                <view class="hot-list-item-right padding-left-sm padding-tb-xs">
                  <view class="name text-lg flex justify-start">{{ item.name }}
                    <view class="search text-gray text-df margin-left-sm" style="font-style: italic">
                      {{ item.searchCount! * 100 }}
                      <text v-show="item.searchCount! > 100" class="cuIcon-hot line-red"></text>
                    </view>
                  </view>
                  <view class="score flex justify-start align-center">
                    <uni-rate :value="item.score! / 20" allow-half color="#c7c7c7" readonly size="18" />
                    <text class="text-awGreen margin-left-xs text-lg ">{{ Number(item.score! / 10).toFixed(1) }}</text>
                  </view>
                  <text class="desc text-df text-gray">
                    {{ item.desc }}
                  </text>
                  <view class="justify-end text-sm  margin-top-xs"
                        style="max-width: 420rpx;max-height:30rpx;overflow: hidden">
                    <text v-for="(tag, tagIndex) in item.tags?.split(',')" :key="tag + tagIndex"
                          class="cu-tag round margin-right-xs bg-gray sm" style="color: #8d8d8d">
                      {{ tag }}
                    </text>
                  </view>
                </view>
              </view>
              <view class="flex justify-center align-center margin-bottom-xl text-gray" style="width: 100%">
                榜单只展示前50的动物哟ヾ(≧▽≦*)o
              </view>
            </scroll-view>

          </swiper-item>
        </swiper>
      </view>
    </view>
  </view>
</template>


<style lang="scss" scoped>
@import "./components/styles/hot";
</style>
